package Controller;

import Service.IUserService;
import Service.UserServiceImpl;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest req, HttpServletResponse resp)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //request获取前台页面的输入信息
        String username = req.getParameter("username");
        String pass = req.getParameter("password");
        //创建一个User实例,接受前台获取的数据为参数
        User user = new User(username, pass);
        //创建服务对象，调用登录方法
        IUserService userService = new UserServiceImpl();
        //将User实例作为userService的login方法的参数，判断该user实例是否存在数据库中。(返回值)
        if (userService.login(user) != null) {
            //重定向至成功页面
            resp.sendRedirect("success.jsp");
        } else {
            //重定向至失败页面
            resp.sendRedirect("fail.jsp");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
